package cn.haixiang._04delay;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @BelongsProject: rocketmq-demo
 * @BelongsPackage: cn.itsource._01_sync
 * @Author: Director
 * @CreateTime: 2022-09-14  11:59
 * @Description: 同步消息消费者
 * @Version: 1.0
 */
public class Consumer {

    public static void main(String[] args) throws Exception{
        // 1.实例化消费者
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("consumer_delay_group");
        // 2.设置NameServer的地址
        consumer.setNamesrvAddr("localhost:9876");

        // 订阅一个或者多个Topic,消费者主题必须跟生产者的主题一致才能获取到消息，以及Tag来过滤需要消费的消息
        // 1.生产者主题  2.*该主题下面的所有二级，我们也可以指定获取那个消息
        consumer.subscribe("delay_topic", "delay_tag");
        // 注册回调实现类来处理从broker拉取回来的消息
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                try {
                    // 1.遍历消息集合
                    for (MessageExt msg : msgs) {
                        // 2.得到消息对象
                        System.out.println(new String(msg.getBody(), StandardCharsets.UTF_8));
                    }
                    // 消费成功，消息签收
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 如果消费失败，重新发一次消息
                return ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }
        });
        // 启动消费者实例
        consumer.start();
    }
}
